<template>
  <div class="app-container">


  <!-- vxe检索数据组件 -->
  <search-form  
    ref="searchForm"
    :formSearchData.sync="formSearchData"
    @searchEventEmit="searchEventEmit"
    @resetSearchEventEmit="resetSearchEventEmit"
    >
  </search-form>


  <!-- 表格组件 -->
  <ex-base-table
    ref="exBaseTable"
    :tableColumn="tableColumn"
    :tableData="tableData"
    :loading.sync="loading"
    :isVxeColSeq="false"
    :isVxeToolbar="true"
    :isVxeCheckbox="false"
    :isVxeHandleS="true"
    @handleRemoveEmit="handleRemoveEmit"
    @handleCreateEmit="handleCreateEmit"
    @handleUpdateEmit="handleUpdateEmit"
    @handleRmoveColEmit="handleRmoveColEmit"
    @customSortMethodEmit="customSortMethodEmit"
    >

    <template v-slot:vxeToolsButtonsExtend>
      <!-- 新增buttons -->
      <el-button size="mini" v-if="isCreateTimeLimitBtn" @click="handleCreateTimeLimit" type="diyfirst">新增期限</el-button>
      <el-button size="mini" v-if="isUpdateTimeLimitBtn" @click="handleUpdateTimeLimit" type="diyfirst">修改期限</el-button>
    </template>

  </ex-base-table>

    <!-- 分页组件 -->
  <Pagination 
    v-show="tablePage.totalResult>0" 
    :total="tablePage.totalResult" 
    :page.sync="tablePage.currentPage" 
    :limit.sync="tablePage.pageSize" 
    @pagination="pageFindList" 
    />


    <!-- 表单提价组件 -->
    <submit-form
      ref="submitForm"
      :dialogFormVisible.sync="dialogFormVisible"
      :dialogStatus="dialogStatus"
      :formSubmitData="formSubmitData"
      :TcOptions="TcOptions"
      @handleFromUpdateDataEmit="handleFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleFromCreateDataEmit"
      @resetFormDataEmit="resetFormSubmitData"
      >
    </submit-form>

    <!-- 期限表单 -->
    <time-limit-submit-form
      ref="timeLimitSubmitForm"
      :dialogFormVisible.sync="timeLimitDialogFormVisible"
      :dialogStatus="timeLimitDialogStatus"
      :formSubmitData="timeLimitFormSubmitData"
      :termCodeOptions="termCodeOptions"
      @handleFromUpdateDataEmit="handleTimeLimitFromUpdateDataEmit"
      @handleFromCreateDataEmit="handleTimeLimitFromCreateDataEmit"
      @resetFormDataEmit="resetTimeLimitFormSubmitData"
      >

    </time-limit-submit-form>


  </div>
</template>

<script>
// 这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
// import PageHeaderLayout from '@/layouts/PageHeaderLayout'
// import ApeDrawer from '@/components/ApeDrawer'
// import { mapGetters } from 'vuex'
import XEUtils from 'xe-utils'
import { 
  fetchListTerm,
  deleteTerm,
  addTerm,
  updateTerm,
  TermCom,
  addTermDate,
  updateTermDate,
  findTermcodename,
  updatefindTermcodename,
  addterm_code
  } from './service/baseApi'

// 基础表格组件
import ExBaseTable from '@/components/VxeTable/ExBaseTable'
// 分页
import Pagination from '@/components/Pagination' 
// 基础表单
import SubmitForm from './components/SubmitForm'
// 检索表单
import SearchForm from './components/SearchForm'
// 期限表单
import TimeLimitSubmitForm from './components/TimeLimitSubmitForm'

import resetFormSubmitData from '@/views/mixins/resetFormSubmitData'
export default {
  name: 'vxe-basetable',
  mixins:[resetFormSubmitData],
  components: {
    ExBaseTable,
    Pagination,
    SubmitForm,
    SearchForm,
    TimeLimitSubmitForm
  },
  props:{
    /* 当前行数据 */
    currentRow:{
      type:Object,
      default(){
        return {

        }
      }
    }
  },
  // 定义属性
  data() {
    return {
        // 检索条件
        formSearchData: {
           
        },
        // 排除条件
        sortField:'',
        sortFlag:'',

      /* 表单相关 */
      dialogFormVisible: false, // 修改删除弹出框
      dialogStatus: '',
      // 表单数据对象
      formSubmitData: {
        id: '',
        term_code: '',
        term_name: '',
        term_value: '',
        term_com: '',
        remark:'',
      },
      initFormSubmitData:{
        id: '',
        term_code: '',
        term_name: '',
        term_value: '',
        term_com: '',
        remark:'',
      },
      TcOptions:[],
      /* 期限表单相关 */
      timeLimitDialogFormVisible: false, // 修改删除弹出框
      timeLimitDialogStatus: '',
      // 表单数据对象
      timeLimitFormSubmitData: {
        s_date:'',
        e_date:'',
        term_code:[]
      },
      initTimeLimitFormSubmitData:{
        s_date:'',
        e_date:'',
        term_code:[]
      },
      termCodeOptions:[],
      termCodeOptionsAdd:[],
      termCodeOptionsUpdate:[],
      isCreateTimeLimitBtn:true, // 是否有新增期限按钮
      isUpdateTimeLimitBtn:true, // 是否有修改期限按钮

       /* 分页相关 */
      tablePage: {
          currentPage: 1, //当前页
          pageSize: 10,  // 每一页页数
          totalResult: 0
      },
      /* 表格相关 */
        tableColumn:[], // 表格字段
        loading: false, //表格loading特效
        tableData: [],  //表格数据

        /* 子表相关 */
        DialogSonTableVisible:false,
    } //datareturn-end

  },
  // 计算属性，会监听依赖属性值随之变化
  computed: {
  },
  // 监控data中的数据变化
  watch: {
    currentRow:{
      handler(n,o){
        this.findList()
        this.findFindTermcodename()
        this.findUpdatefindTermcodename()
      },
      immediate: true
    }
  },
  // 方法集合
  methods: {
    /* API数据操作相关 */
    async getAddtermCode() {
      return await addterm_code({
        m_id:this.currentRow.id
      }).then(({data}) => {
        return data.rows.term_code
      })
    },

    //查询相关id所有期限数据-适配新增
    findFindTermcodename(){
      findTermcodename({
        m_id:this.currentRow.id
      }).then(({data}) => {
        this.termCodeOptionsAdd = data.rows
      })
    },
    //查询相关id所有期限数据-适配修改
    findUpdatefindTermcodename(){
      updatefindTermcodename({
        m_id:this.currentRow.id
      }).then(({data}) => {
        this.termCodeOptionsUpdate = data.rows
      })
    },


    
    // 查询数据
    async findList() {
        this.loading = await true
        // 请求表格数据
        await  fetchListTerm({
          page:this.tablePage.currentPage, // 当前页
          pageSize:this.tablePage.pageSize, // 每页条数
          sortField:this.sortField,
          sortFlag:this.sortFlag,
          m_id:this.currentRow.id,
          ...this.formSearchData,  //检索条件
          }).then(({data}) => {
            // 给表格数据赋值
            this.tableData = data.rows
            // 给分页总数赋值
            this.tablePage.totalResult = data.total
            // 关闭加载特效
            setTimeout(() => {
                this.loading = false
            }, 0.5 * 1000)
        })

        await this.findFindTermcodename()
        await this.findUpdatefindTermcodename()

    },
    findTc() {
        TermCom({  
          ...this.formSearchData,  //检索条件
          }).then(({data}) => {
            this.TcOptions = data

        })
    },
    pageFindList(){
      this.findList()
    },
    /* 表格组件相关 */
    // 初始化表格字段
    initTableCols(){
     const tabCols = [  //动态增加的字段 传进来的
            { field: 'vaild_time', title: '有效时间段', width: 400 , sortable:true},
            { field: 'term_name', title: '期限名称', width: 300 },
            { field: 'term_value', title: '期限数值', width: 300 },
            { field: 'term_com', title: '期限单位', width: 300 },
            // { field: 's_date', title: '生效日期', width: 200 },
            // { field: 'e_date', title: '失效日期', width: 200 },
            { field: 'remark', title: '备注', width: 300 }
        ]
        this.tableColumn = tabCols;
    },
    // 表格工具组-多选删除
    handleRemoveEmit(selectRecords){
       batchDeleteParamterszi({
          ...selectRecords
          }).then(({data}) => {
            this.findList()           
        })
    },
    // 表格工具组-新增表单弹窗（需要表单组件）
    handleCreateEmit(type){

      this.getAddtermCode().then((term_code) => {
        // 重置表单内容
        this.resetFormSubmitData({
          replaceObj: {
            term_code
          }
        })
        this.dialogStatus = type
        this.dialogFormVisible = true
        this.$nextTick(() => {
            this.$refs.submitForm.$refs['dataForm'].clearValidate()
        })
      })


      
    },
    // 行内按钮-修改数据弹窗（需要表单组件）
  handleUpdateEmit(row,type){
      this.formSubmitData = Object.assign({}, row) // copy obj
      this.dialogStatus = type
      this.dialogFormVisible = true
      this.$nextTick(() => {
          this.$refs.submitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 单行删除
    handleRmoveColEmit(row){
       deleteTerm({
         m_id:this.currentRow.id,
         s_date:row.s_date,
         id: row.id,
         e_date: row.e_date
          }).then(({data}) => {
            this.findList()
        })
    },
    /* 表单组件相关 */
    // 更新
    handleFromUpdateDataEmit(){
       updateTerm({
          ...this.formSubmitData,  //检索条件
          }).then(({data}) => {
            this.findList()            
        })
    },
    // 增加
    handleFromCreateDataEmit(){
         addTerm({
           m_id:this.currentRow.id,
          ...this.formSubmitData,  //检索条件
          }).then(({data}) => {
            this.findList()
        })
    },
    /* 期限表单相关 */
    /**
     *  重置表单内容
     *  obj ：重置默认值
     *  replaceObj ：重置需要替换的默认值
     */
    resetTimeLimitFormSubmitData(obj = {}) {

       let newObj, resetObj, replaceObj, exclude
      // 没有重置对象默认重置所有值 isUndefined
      if (XEUtils.isUndefined(obj.resetObj) || XEUtils.isEmpty(obj.resetObj)) {
        resetObj = XEUtils.isEmpty(this.initTimeLimitFormSubmitData)? {} : this.initTimeLimitFormSubmitData
      } else {
        resetObj = obj.resetObj
      }
      // 替换（重置值）中的值：比如修改时需要回显的值
      replaceObj = obj.replaceObj || {}
      newObj = XEUtils.merge(resetObj, replaceObj)
      // 排除不重置的字段
      if (!XEUtils.isUndefined(obj.exclude) && !XEUtils.isEmpty(obj.exclude)) {
        exclude = obj.exclude
        XEUtils.arrayEach(exclude, (item, key) => {
          delete newObj[`${item}`];
        })
      }
      this.timeLimitFormSubmitData = XEUtils.merge(this.timeLimitFormSubmitData, newObj)
    },
    // 弹窗-新增
    handleCreateTimeLimit(){
      // 重置表单内容
      this.resetTimeLimitFormSubmitData({
        replaceObj:{
          s_date: '',
          e_date: '9999-12-31',
          term_code:''
        }
      })

      this.termCodeOptions = this.termCodeOptionsAdd
      this.timeLimitDialogStatus = 'create'
      this.timeLimitDialogFormVisible = true
      
      this.$nextTick(() => {
          this.$refs.timeLimitSubmitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 弹窗-修改
    handleUpdateTimeLimit(){
      // 重置表单内容
      this.resetTimeLimitFormSubmitData({
        replaceObj:{
          s_date: '',
          e_date: '',
          term_code:''
        }
      })

      this.termCodeOptions = this.termCodeOptionsUpdate
      this.timeLimitDialogStatus = 'update'
      this.timeLimitDialogFormVisible = true
      
      this.$nextTick(() => {
          this.$refs.timeLimitSubmitForm.$refs['dataForm'].clearValidate()
      })
    },
    // 操作-修改
    handleTimeLimitFromUpdateDataEmit(){
       this.timeLimitFormSubmitData.term_code = this.timeLimitFormSubmitData.term_code.join(",")
      updateTermDate({
          m_id:this.currentRow.id,
          ...this.timeLimitFormSubmitData,  //检索条件
          }).then(({data}) => {
            this.findList()            
        })
    },
    // 操作-新增
    handleTimeLimitFromCreateDataEmit(){
      this.timeLimitFormSubmitData.term_code = this.timeLimitFormSubmitData.term_code.join(",")
      addTermDate({
           m_id:this.currentRow.id,
          ...this.timeLimitFormSubmitData,  //检索条件
          }).then(({data}) => {
            this.findList()         
        })
    },

    /* 检索相关 */
    // 检索
    searchEventEmit() {
      this.tablePage.currentPage = 1
      this.findList()
    },
    // 重置
    resetSearchEventEmit(){
      // 重置代码...
      this.tablePage.currentPage = 1
      this.findList()
    },
    /* 排序 */
    customSortMethodEmit(property, order){
      this.sortField = property
      this.sortFlag = order
      this.findList()
    },

  /* 子表格弹出 */
    viewSonTable(row){
        this.DialogSonTableVisible = true
    }
  }, //method-end
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {
    // 初始化表格字段
    this.initTableCols()
    // 初始化表格数据
    this.findList()
    this.findTc()
    

  },
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    
  },
  beforeCreate() {}, // 生命周期 - 创建之前
  beforeMount() {}, // 生命周期 - 挂载之前
  beforeUpdate() {}, // 生命周期 - 更新之前
  updated() {}, // 生命周期 - 更新之后
  beforeDestroy() {}, // 生命周期 - 销毁之前
  destroyed() {}, // 生命周期 - 销毁完成
  activated() {}, // 如果页面有keep-alive缓存功能，这个函数会触发
}
</script>

<style lang='scss' scoped>


  .my-dropdown4 {
    width: 600px;
    height: 300px;
    background-color: #fff;
    border: 1px solid #dcdfe6;
    box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  }
</style>